//
//  MessageDetailViewController.m
//  cliqset
//
//  Created by David Hinson on 3/31/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "MessageDetailViewController.h"
#import "cliqsetAppDelegate.h"
#import "Message.h"

@implementation MessageDetailViewController

@synthesize profile;
@synthesize hoverView;
@synthesize footer;
@synthesize header;
@synthesize myName;
@synthesize myStatus;
@synthesize myStamp;
@synthesize index;
@synthesize deleteMessageBtn;
@synthesize replyView;

@synthesize subjectField;
@synthesize recipientField;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	

    [super viewDidLoad];
	
	Message * message = (Message *)[myApp.messages objectAtIndex:self.index];
	self.title = [NSString stringWithFormat:@"%@ %@", message.sender.givenName == nil ? @"" : message.sender.givenName, message.sender.familyName == nil ? @"" : message.sender.familyName];
	
	[self loadFooter];
	//[self loadHeader];
	
	UIBarButtonItem *replyButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(replyToMessage:)] autorelease];
	self.navigationItem.rightBarButtonItem = replyButton;
	
    hoverView.center  = [self view].center;
	
	[[self view] addSubview:hoverView];
    [[self view] bringSubviewToFront:hoverView];

	replyView.parent = self;
    replyView.center = [self view].center;
	
	CGRect adjFrame    = replyView.frame;
	adjFrame.origin.y += 20;
	replyView.frame    = adjFrame;
	
	replyView.replyField.text   = @"";
	
	[[self view] addSubview:replyView];
    [[self view] bringSubviewToFront:replyView];
	
	[self showReplyView:NO];
	
	[myApp resetUnreadMessages];
}

// Reply to message...
-(void)replyToMessage:(id)id {
	NSLog(@"replyToMessage");
	[self showReplyView:YES];
	[self.replyView.replyField becomeFirstResponder];
}

- (void)showReplyView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show){
		self.navigationItem.leftBarButtonItem.enabled  = NO;
		self.navigationItem.rightBarButtonItem.enabled = NO;
		replyView.alpha = 0.85;
		}
	else {
		self.navigationItem.leftBarButtonItem.enabled  = YES;
		self.navigationItem.rightBarButtonItem.enabled = YES;
		replyView.alpha = 0.0;
		}
	
	[UIView commitAnimations];
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

// Create Table Footer
-(void)loadFooter {
		
	self.footer = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 120.0)] retain];
	UILabel * prompt = [[UILabel alloc] initWithFrame:CGRectMake(0.0, -10.0, 320.0, 80.0)];

	UIFont* bold_large_font   = [UIFont boldSystemFontOfSize:20];
	
	prompt.backgroundColor = [UIColor clearColor];
	prompt.textColor       = [UIColor whiteColor];
	prompt.text            = @"Delete Message";
	prompt.textAlignment   = UITextAlignmentCenter;
	prompt.font            = bold_large_font;
	
	self.deleteMessageBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	self.deleteMessageBtn.frame = CGRectMake(10.0, 10.0, 300.0, 40.0);
	[self.deleteMessageBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
	
	[self.deleteMessageBtn addTarget:self action:@selector(deleteMessage:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *img = [UIImage imageNamed:@"delete-contact-without-text.png" ] ;
	[self.deleteMessageBtn setBackgroundImage:img forState:UIControlStateNormal];
	
	[self.footer addSubview:self.deleteMessageBtn];
	[self.footer addSubview:prompt];
	[prompt release];
	
	self.profile.tableFooterView = self.footer;
}

// Process menu button clicks
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	// Dereference our message
	
	Message * message = (Message*)[myApp.messages objectAtIndex:self.index];
	switch (buttonIndex) {
		case 0:			
			[myApp showMessagesHoverView:YES];
			
			// Remove from the display NOW.
			// [myApp.messages removeObjectAtIndex:self.index];
			// [myApp reloadBGMessagesTable];
			
			// Delete the message
			[myApp.cliqset deleteMessage:message.messageIdentifier messageIndex:self.index];
			
			break;
		default:
			break;
	}
}

// Delete message
-(void)deleteMessage:(id)id {
	
	UIActionSheet* myAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	
	[myAction addButtonWithTitle:@"Delete Message"];
	[myAction addButtonWithTitle:@"Cancel"];
	
	myAction.destructiveButtonIndex=0;
	myAction.cancelButtonIndex=1;
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[myAction showInView:[myApp window]];
	
	[myAction release];
}

// Load table header
-(void)loadHeader {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	
	
	Message * message = (Message *)[myApp.messages objectAtIndex:self.index];
	
	NSData* imageData;
	UIImage * graphic;
	UIImageView *showImage;
	
	self.header               = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] retain];
	UIColor* textColor        = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	// Fonts for Labels
	UIFont* eeeny_teeny_font  = [UIFont systemFontOfSize:10];
	UIFont* teeny_font        = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font   = [UIFont boldSystemFontOfSize:18];
	
	imageData = message.sender.avatarBlob;
	graphic = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
	// Allocate image
	showImage        = [[UIImageView alloc] initWithFrame:CGRectMake(230.0, 10.0, 80.0, 80.0 * (graphic.size.height / graphic.size.width))];
	showImage.opaque = NO;    
	showImage.image  = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[self.header addSubview:imageBackground];
	[imageBackground release];
	
	// Add picture to the cell
	[self.header addSubview:showImage];
	
	[showImage release];
	[graphic release];
	
	// Allocate Labels
	self.myName   = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 225, 20.0)] retain];
	
	CGSize constraintSize;
	constraintSize.width      = 250.0f;
	constraintSize.height     = MAXFLOAT;	
	CGSize offsetX            = [message.subject sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
	self.myStatus             = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 35.0, 225.0, offsetX.height)] retain];
	
	// Set name label
	self.myName.text = [NSString stringWithFormat:@"%@ %@", message.sender.givenName == nil ? @"" : message.sender.givenName, message.sender.familyName == nil ? @"" : message.sender.familyName];
	self.myName.font = bold_large_font;
	
	// Set Status
	myStatus.text       = message.subject;
	self.myStatus.font  = teeny_font;
	
	self.myStamp  = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 10 + self.myName.frame.size.height + self.myStatus.frame.size.height, 225.0, 20.0)] retain];
	
	NSDate * tsDate   = [myApp dateFromISO8601:message.timeSent];
	self.myStamp.text = [myApp describeEventTimeStamp:tsDate];
	self.myStamp.font = eeeny_teeny_font;
	
	// Set label background color
	self.myName.backgroundColor   = [UIColor clearColor];
	self.myStatus.backgroundColor = [UIColor clearColor];
	self.myStamp.backgroundColor  = [UIColor clearColor];
	
	// Set text color
	self.myName.textColor       = textColor;
	self.myStatus.textColor     = textColor;
	self.myStamp.textColor      = textColor;
	
	self.myStatus.numberOfLines = 0;
	self.myStatus.lineBreakMode = UILineBreakModeWordWrap;
	
	// Add labels to the cell
	[header addSubview:self.myName];
	[header addSubview:self.myStatus];
	[header addSubview:self.myStamp];
	
	self.profile.tableHeaderView = header;
}

#pragma mark ---- Header handling ----

-(void)setHeaderName:(NSString*)name {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	
	
	self.myName.text        = name;
	NSData * imageData      = myApp.currentProfile.basicProfile.avatarBlob;
	UIImage * graphic       = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
	// Allocate image
	UIImageView * showImage = [[UIImageView alloc] initWithFrame:CGRectMake(230.0, 10.0, 80.0, 80.0 * (graphic.size.height / graphic.size.width))];
	showImage.opaque        = NO;    
	showImage.image         = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[self.header addSubview:imageBackground];
	[imageBackground release];
	
	// Add picture to the cell
	[self.header addSubview:showImage];
	
	[showImage release];
	[graphic release];
}

-(void)setHeaderStatus:(NSString*)newStatus timestamp:(NSString*)timestamp {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	
	UIFont* teeny_font        = [UIFont systemFontOfSize:14];
	
	CGSize constraintSize;
	constraintSize.width        = 215;
	constraintSize.height       = MAXFLOAT;	
	CGSize offsetX1             = [[NSString stringWithFormat:@"\"%@\"", newStatus] sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
	
	self.myStatus.text          = [NSString stringWithFormat:@"\"%@\"", newStatus];
	
	CGRect newFrame2            = CGRectMake(self.myStatus.frame.origin.x, self.myStatus.frame.origin.y, 215, offsetX1.height);
	self.myStatus.frame         = newFrame2;
	self.myStatus.numberOfLines = 0;
	
	CGRect newFrame1            = CGRectMake(self.myStamp.frame.origin.x, 30 + offsetX1.height, 215, self.myStamp.frame.size.height);
	self.myStamp.frame          = newFrame1;	
	
	NSDate * tsDate   = [myApp dateFromISO8601:timestamp];
	self.myStamp.text = [myApp describeEventTimeStamp:tsDate];
	
	if (self.myStatus.frame.size.height + 30 > self.header.frame.size.height) {
		CGRect headerFrame = self.profile.tableHeaderView.frame;
		headerFrame.size.height      = self.myStatus.frame.size.height + 50;
		self.header.frame            = headerFrame;
		self.profile.tableHeaderView = self.header;
	}
}

-(void)setHeaderStatus:(NSString*)status timeStamp:(NSDate*)timeStamp {
	
	cliqsetAppDelegate* myApp   = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];	
	UIFont* teeny_font          = [UIFont systemFontOfSize:14];
	
	CGSize constraintSize;
	constraintSize.width        = 215;
	constraintSize.height       = MAXFLOAT;	
	CGSize offsetX1             = [[NSString stringWithFormat:@"\"%@\"", status] sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
	
	self.myStatus.text          = [NSString stringWithFormat:@"\"%@\"", status];
	
	CGRect newFrame2            = CGRectMake(self.myStatus.frame.origin.x, self.myStatus.frame.origin.y, 215, offsetX1.height);
	self.myStatus.frame         = newFrame2;
	self.myStatus.numberOfLines = 0;
	
	CGRect newFrame1            = CGRectMake(self.myStamp.frame.origin.x, 30 + offsetX1.height, 215, self.myStamp.frame.size.height);
	self.myStamp.frame          = newFrame1;	
	self.myStamp.text           = [myApp describeEventTimeStamp:timeStamp];
	
	if (self.myStatus.frame.size.height + 30 > self.header.frame.size.height) {
		CGRect headerFrame = self.profile.tableHeaderView.frame;
		headerFrame.size.height      = self.myStatus.frame.size.height + 50;
		self.header.frame            = headerFrame;
		self.profile.tableHeaderView = self.header;
	}
}

#pragma mark ---- table handling ----

-(void)reloadData {
	[self.profile reloadData];
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 3;
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	CGSize constraintSize;
	constraintSize.width = 300.0f;
	constraintSize.height = MAXFLOAT;
	Message * message;

	switch (indexPath.row) {
		case 0:
			return 40;
			break;
		case 1:
			return 40;
			break;
		case 2:			
			message = (Message *)[myApp.messages objectAtIndex:self.index];
			CGSize offset    = [message.body sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
			return offset.height + 20;
			break;
	}
	
	return 40;
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
	
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];	
	
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	

	cell.textColor  = textColor;
	
	Message * message = (Message *)[myApp.messages objectAtIndex:self.index];
	
	CGSize constraintSize;
	constraintSize.width = 300.0f;
	    
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
		
	switch (indexPath.row) {
		case 0:
			self.recipientField = [[UILabel alloc] initWithFrame:CGRectMake(80, 5, 240, 30)];
			self.recipientField.textColor = textColor;
			self.recipientField.font = [UIFont systemFontOfSize:16];
			self.recipientField.text = [NSString stringWithFormat:@"%@ %@", message.sender.givenName == nil ? @"" : message.sender.givenName, message.sender.familyName == nil ? @"" : message.sender.familyName];
			
			[cell addSubview:self.recipientField];
			
			UILabel * to     = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 70, 30)];
			to.font          = [UIFont boldSystemFontOfSize:16];
			to.textColor     = textColor;
			to.text          = @"To:";
			to.textAlignment = UITextAlignmentRight;
			[cell addSubview:to];
			[to release];
			
			break;
		case 1:
			self.subjectField   = [[UITextField alloc] initWithFrame:CGRectMake(80, 10, 240, 30)];
			self.subjectField.textColor = textColor;
			self.subjectField.font = [UIFont systemFontOfSize:16];
			self.subjectField.text = message.subject;
			
			[cell addSubview:self.subjectField];
			
			UILabel * subj   = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 70, 30)];
			subj.font          = [UIFont boldSystemFontOfSize:16];
			subj.textColor     = textColor;
			subj.text          = @"Subject:";
			subj.textAlignment = UITextAlignmentRight;
			[cell addSubview:subj];
			[subj release];
			
			break;
		case 2:
			constraintSize.height = MAXFLOAT;
			
			CGSize offset    = [message.body sizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
			
			UILabel * messageView = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, offset.height)];
			
			messageView.textColor     = textColor;
			messageView.text          = [NSString stringWithFormat:@"%@", message.body];
			messageView.font          = [UIFont systemFontOfSize:16];
			messageView.numberOfLines = 0;
			
			[cell addSubview:messageView];
			[messageView release];
			break;
	}
	
	return cell;
}	

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

// Refresh
-(IBAction)doRefresh:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	[self showHoverView:YES];
	[myApp.cliqset loadProfileEvents:myApp.userString reload:YES];
	[myApp.cliqset getCurrentStatus];
}

- (void)dealloc {
	[subjectField release];
	[recipientField release];
	[deleteMessageBtn release];
	[footer release];
	[header release];
	[myName release];
	[myStatus release];
	[myStamp release];
	[hoverView release];
	[replyView release];
	[profile release];
    [super dealloc];
}

@end
